"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '28/05/2024'
    comment: 用户意图接口
"""
import ujson
from datetime import datetime
from fastapi import APIRouter, Request, Body, responses

from config import Config
from project.lib.decorator import api_common, exec_duration
from project.core.function import json_response
from project.model.basic import User
from project.service.agents.agent import Agent
from project.service.agents.hr import HRService
from project.lib.common import logger
from project.core.log import Colors


hr_router = APIRouter(prefix='', tags=['HR面试'])


@hr_router.post('/hr/user/memories/init', summary='清空面试记忆')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def init_user_memories(request: Request, dev_id: str = Body(..., title='设备id', embed=True)):
    """
    **desc**: 清空用户记忆

    **url**: http(s)://{0}.udicaria.com/hr/user/memories/init

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    user = User(dev_id=dev_id)
    agent = Agent(user, user_message='', memories_key='recruit')
    agent.init_user_memories()

    return json_response()


@hr_router.post('/hr/user/memories/add', summary='添加面试记忆')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def add_user_memories(request: Request,
                            dev_id: str = Body(..., title='设备id'),
                            user_message: str = Body('', title='用户话术'),
                            agent_message:  str = Body('', title='agent话术'),):
    """
    **desc**: 添加面试记忆

    **url**: http(s)://{0}.udicaria.com/hr/user/memories/add

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    now_str = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
    user = User(dev_id=dev_id)
    agent = Agent(user, user_message='', memories_key='recruit')
    if user_message:
        agent.add_user_memories(now_str + " 对方向你说: " + user_message)
    if agent_message:
        agent.add_user_memories(now_str + " 你向对方说: " + agent_message)

    return json_response()


@hr_router.post('/hr/interview', summary='面试回复')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_interview(request: Request,
                       dev_id: str = Body(..., title='设备id'),
                       user_message: str = Body('', title='用户话术')):
    """
    **desc**: 面试回复

    **url**: http(s)://{0}.udicaria.com/hr/interview

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    user = User(dev_id=dev_id)
    response = await HRService.interview(user, user_message)

    return json_response(data={'response': response})


@hr_router.post('/hr/progress', summary='面试进度')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_progress(request: Request,
                      dev_id: str = Body(..., title='设备id'),
                      user_message: str = Body(..., title='用户话术')):
    """
    **desc**: 面试进度

    **url**: http(s)://{0}.udicaria.com/hr/progress

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    user = User(dev_id=dev_id)
    last_number, total_question_number = await HRService.progress(user, user_message)

    return json_response(data={'schedule': f'{last_number}/{total_question_number}'})


@hr_router.post('/hr/interview/streaming', summary='面试回复')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_interview_streaming(request: Request,
                                 dev_id: str = Body(..., title='设备id'),
                                 user_message: str = Body('', title='用户话术')):
    """
    **desc**: 面试回复(流式)

    **url**: http(s)://{0}.udicaria.com/hr/interview

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    user = User(dev_id=dev_id)
    response_stream = await HRService.interview_streaming(user, user_message)

    return responses.StreamingResponse(response_stream, media_type='text/plain')


@hr_router.post('/hr/detect/talker', summary='推测角色')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_detect_talker(request: Request,
                           dev_id: str = Body(..., title='设备id'),
                           user_message: str = Body(..., title='用户话术')):
    """
    **desc**: 招聘中推测用户角色

    **url**: http(s)://{0}.udicaria.com/hr/detect/talker

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    user = User(dev_id=dev_id)
    talker = await HRService.detect_talker(user, user_message)

    return json_response(data={'talker': talker})


@hr_router.post('/hr/load/agent', summary='加载智能体')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def load_agent(request: Request,
                     dev_id: str = Body(..., title='设备id'),
                     rich_text: str = Body(..., title='面试智能体富文本')):
    """
    **desc**:

    **url**: http(s)://{0}.udicaria.com/hr/load/agent

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            rich_text: 面试富文本

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    logger.info(rich_text, font_color=Colors.PURPLE.value)

    agent_info = await HRService.save_agent_sop(dev_id, rich_text)

    logger.info(ujson.dumps(agent_info, ensure_ascii=False, indent=4), font_color=Colors.PURPLE.value)
    return json_response(data=agent_info)


@hr_router.post('/hr/interview/streaming/sop', summary='面试回复(sop)')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_interview_streaming_sop(request: Request,
                                     dev_id: str = Body(..., title='设备id'),
                                     user_message: str = Body('', title='用户话术')):
    """
    **desc**: 面试回复(流式)

    **url**: http(s)://{0}.udicaria.com/hr/interview/streaming/sop

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    response_stream = await HRService.interview_streaming_sop(dev_id, user_message)

    return responses.StreamingResponse(response_stream, media_type='text/plain')


@hr_router.post('/hr/progress/sop', summary='面试进度(sop)')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_progress_sop(request: Request,
                          dev_id: str = Body(..., title='设备id'),
                          user_message: str = Body(..., title='用户话术')):
    """
    **desc**: 面试进度(sop)

    **url**: http(s)://{0}.udicaria.com/hr/progress/sop

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    last_number, total_question_number = await HRService.progress_sop(dev_id, user_message)

    return json_response(data={'schedule': f'{last_number}/{total_question_number}'})


@hr_router.post('/hr/report/streaming/sop', summary='面试报告(sop)')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_report_streaming_sop(request: Request,
                                  dev_id: str = Body(..., title='设备id'),
                                  user_message: str = Body(..., title='用户话术')):
    """
    **desc**: 面试报告(sop)

    **url**: http(s)://{0}.udicaria.com/hr/report/streaming/sop

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id
            user_message: 用户话术

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    report = await HRService.report_streaming_sop(dev_id, user_message)

    return responses.StreamingResponse(report, media_type='text/plain')


@hr_router.post('/hr/result/sop', summary='面试结果(sop)')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_result_sop(request: Request, dev_id: str = Body(..., title='设备id', embed=True)):
    """
    **desc**: 面试结果(sop)

    **url**: http(s)://{0}.udicaria.com/hr/result/sop

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    data = await HRService.result_sop(dev_id)

    return json_response(data=data)


@hr_router.post('/hr/result/streaming/sop', summary='面试结果(流式)(sop)')
@api_common(doc_replace=(('{0}', Config.HTTP_DOC_FIX),))
@exec_duration(add_return=True)
async def do_result_streaming_sop(request: Request, dev_id: str = Body(..., title='设备id', embed=True)):
    """
    **desc**: 面试结果(sop)

    **url**: http(s)://{0}.udicaria.com/hr/result/streaming/sop

    **method**: POST

    **params**:

        <body>:
            dev_id: 设备id

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    data = await HRService.result_sop_streaming(dev_id)

    return responses.StreamingResponse(data, media_type='text/plain')




